<template>
  <el-drawer
    title="高级搜索"
    :visible.sync="visible"
    :size="panelWidth"
    :direction="direction"
    class="flex-y"
  >
    <!-- <base-panel :show.sync="visible" :width="panelWidth"> -->
    <template slot="title">
      <div class="flex-x al-c title-box">
        <div class="font-18 flex-1">高级搜索</div>
        <el-dropdown
          class="pull-right"
          trigger="click"
          @command="setAdvanceSearchColumn"
        >
          <div class="flex-x al-c">
            <i
              class="iconfont icon-xitongguanli customer-panel-btn"
              style="float: none;"
            ></i>
          </div>

          <el-dropdown-menu slot="dropdown" class="customer-advance-setting">
            <el-dropdown-item command="1">一栏</el-dropdown-item>
            <el-dropdown-item command="2">两栏</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </template>
    <div class="bg-w flex-y panel-box">
      <div
        class="task-search-panel-title task-pointer task-flex task-ai"
        @click="show = !show"
      >
        <span class="task-font16">常用查询条件</span>
        <span
          slot="reference"
          class="task-font14 task-c2 task-ml12 task-mr4"
          @click.stop="$refs.searchSetModal.open()"
        >设置</span
        >
        <span class="task-span1">
          <el-tooltip
            content="常用查询条件可以通过“设置”功能，进行添加和修改"
            placement="top"
          >
            <i class="iconfont icon-question task-icon"></i>
          </el-tooltip>
        </span>
        <i
          class="iconfont icon-triangle-down task-f12 task-c9"
          v-if="!show"
        ></i>
        <i class="iconfont icon-up task-icon" v-else></i>
      </div>
      <!-- <el-form label-position="top" class="advanced-search-form" onsubmit="return false;"> -->
      <el-form label-position="top" class="usual-search-form  scroll-y" onsubmit="return false;">
        <search-form
          v-show="show"
          :fields="diyFields"
          ref="searchForm"
          :form-backup="formBackup"
          :column-num="columnNum"
        ></search-form>
      </el-form>
      <slot name="footer"></slot>

      <!-- 设置弹框 -->
      <search-set-modal
        ref="searchSetModal"
        :fields="fields"
        :search-modal-storage="searchModalStorage"
        :search-panel-storage="searchPanelStorage"
        @changeDiyFields="changeDiyFields"
      />
    </div>
    <!-- </base-panel> -->
  </el-drawer>
</template>

<script>
import {
  FormFieldMap,
  SettingComponents,
} from '@src/component/form/components';
import * as Utils from '@src/component/form/util';
import { storageGet, storageSet } from '@src/util/storageV2';
import _ from 'lodash';
import { isEmptyStringObject } from '@src/util/function';

import SearchSetModal from './SearchSetModal';
import { isFunction } from '@src/util/type';

import { getCustomerListAsyn } from '@src/api/CustomerApi';
// import UsualSelect from '@src/component/form/components/FormRelatedCatalog/extend/UsualSelect.vue';

import { formatAddress } from 'pub-bbx-utils';
import { baseDistValueToObject, searchAddressObjectParams} from '@src/util/addressUtil';
export default {
  name: 'search-panel',
  props: {
    config: {
      type: Object,
      default: () => ({}),
    },
    initData: {
      type: Object,
      default: () => ({}),
    },
    searchModalStorage: {
      type: String,
      default: '',
    },
    searchPanelStorage: {
      type: String,
      default: '',
    },
    tableKey:{
      type: String,
      default: '',
    }
  },
  data() {
    return {
      visible: false,
      formBackup: {},
      columnNum: 1,
      selfFields: this.buildSelfFields(),
      show: true,
      diyFields: [],
      direction: 'rtl',
    };
  },
  computed: {
    fields() {
      let f = {};
      let fields = [...this.config.fields, ...this.selfFields]
        .filter((f) =>(f.isSearch || f.isSystem ) && f.formType !== 'doSome')
        .map((field) => {
          f = _.cloneDeep(field);

          let formType = f.formType;

          if (formType === 'datetime') {
            formType = 'date';
          }

          if (f.fieldName === 'customer') {
            formType = 'customer';
          }

          if (formType === 'updateTime') {
            f.displayName = '更新时间';
          }
          // if (formType == 'related_catalog' && f.tableName == 'product') {
          //   // 转换设备类型表单数据
          //   f.fieldName = 'catalogId';
          // }

          return Object.freeze({
            ...f,
            isNull: 1,
            formType,
            originalFormType: f.formType,
            operator: this.matchOperator(f),
          });
        });
      // 去除排序方法
      // .sort((a, b) => a.orderId - b.orderId);
      let obj_ = storageGet(this.searchModalStorage);
      if (obj_) {
        obj_ = JSON.parse(obj_);
        if (obj_.allCheckList.length) {
          this.diyFields = fields.filter(
            (item) => obj_.allCheckList.indexOf(item.fieldName) > -1
          );
        }
      }

      return fields;
    },
    panelWidth() {
      return `${420 * this.columnNum}px`;
    },
  },
  mounted() {
    const { column_number } = this.getLocalStorageData();
    if (column_number) this.columnNum = Number(column_number);

    this.computedWhetherAddQrcodeField();
  },
  methods: {
    buildSelfFields() {
      let fields = [];

      return fields;
    },
    computedWhetherAddQrcodeField() {
      this.selfFields = [
        ...this.selfFields,
      ];
    },
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet(this.searchPanelStorage, JSON.stringify(data));
    },
    getLocalStorageData() {
      const dataStr = storageGet(this.searchPanelStorage) || '{}';
      return JSON.parse(dataStr);
    },
    matchOperator(field) {
      let formType = field.formType;
      let operator = '';

      switch (formType) {
      case 'date': {
        operator = 'between';
        break;
      }
      case 'datetime': {
        operator = 'between';
        break;
      }
      case 'select': {
        if (field.setting && field.setting.isMulti) {
          operator = 'contain';
        } else {
          operator = 'eq';
        }
        break;
      }
      case 'cascader': {
        operator = 'cascader';
        break;
      }
      case 'user': {
        operator = 'user';
        break;
      }
      case 'address': {
        operator = 'address';
        break;
      }
      case 'location': {
        operator = 'location';
        break;
      }
      case 'related_task': {
        operator = 'array_eq';
        break;
      }
      case 'related_catalog': {
        operator = 'eq';
        break;
      }
      case 'formula': {
        operator = 'eq';
        break;
      }
      default: {
        operator = 'like';
        break;
      }
      }
      return operator;
    },
    resetParams() {
      this.formBackup = {};
      this.$refs.searchForm
        && this.$nextTick(this.$refs.searchForm.initFormVal);
    },

    buildParams() {
      let form;
      try {
        form = this.$refs.searchForm.returnData();
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.formBackup = Object.assign({}, form);

      const isSystemFields = this.fields.filter((f) => f.isSystem);
      const notSystemFields = this.fields.filter((f) => !f.isSystem);
      let params = {
        conditions: [],
      };

      let tv = null;
      let fn = '';

      for (let i = 0; i < isSystemFields.length; i++) {
        tv = isSystemFields[i];
        fn = tv.fieldName;

        // hasRemind
        if (fn === 'hasRemind' && form[fn] !== '') {
          params.hasRemind = form[fn] == 2 ? 0 : form[fn];
          continue;
        }

        if (fn === 'qrcodeState' && form[fn] !== '') {
          params.qrcodeState = form[fn] == 2 ? 0 : form[fn];
          continue;
        }

        if (fn == 'area') {
          // 国际化地址组件返回的第一个是国家，非国际化组件第一个返回的是省
          const address = baseDistValueToObject(form[fn]);

          params.productAddress = {
            ...(params.productAddress || {}),
            ...(searchAddressObjectParams(address))
          };
          continue;
        }

        if (fn === 'addressDetail') {
          params.productAddress = {
            ...(params.productAddress || {}),
            address: form[fn],
          };
          continue;
        }

        if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
          continue;
        }

        if (fn === 'customer') {
          let res_ = form[fn];
          res_ = form[fn] && _.isArray(form[fn]) && form[fn].length
            ? form[fn].map((item) => item.id).join(',')
            : '';
          params['customerId'] = res_;
          continue;
        }

        if (['date', 'datetime'].includes(tv.formType)) {
          params[`${fn}Start`] = form[fn][0];
          params[`${fn}End`] = form[fn][1];
          continue;
        }

        if (tv.formType === 'tags') {
          params.tagId = form[fn].map(({ id }) => id).join('');
        }

        if (typeof form[fn] === 'string') {
          params[fn === 'customer' ? 'customerId' : fn] = form[fn];
          continue;
        }

        if (typeof form[fn] === 'number') {
          params[fn] = form[fn];
          continue;
        }

        if (tv.formType == 'related_catalog') {
          let str_ = [];
          let key = 'id';
          if (form[fn].length) {
            form[fn].map((item_) => {
              if (
                tv.hasOwnProperty('attribute')
                && tv.attribute.hasOwnProperty('searchValueKey')
              )
                key = tv.attribute.searchValueKey;
              str_.push(item_[key]);
            });
          } else {
            str_ = form[fn][key];
          }
          params[fn] = str_;
        }
      }
      for (let i = 0; i < notSystemFields.length; i++) {
        let key = null;
        tv = notSystemFields[i];
        fn = tv.fieldName;

        if (!form[fn] || (Array.isArray(form[fn]) && !form[fn].length)) {
          continue;
        }

        // 空对象
        if (
          typeof form[fn] === 'object'
          && !Array.isArray(form[fn])
          && !Object.keys(form[fn]).length
        ) {
          continue;
        }

        if (['date', 'datetime'].includes(tv.originalFormType)) {
          params.conditions.push({
            property: fn,
            operator: tv.operator,
            betweenValue1: form[fn][0],
            betweenValue2: form[fn][1],
          });
          continue;
        }

        if (tv.formType === 'cascader') {
          params.conditions.push({
            property: fn,
            operator: tv.operator,
            inValue: form[fn],
          });
          continue;
        }

        if (tv.formType === 'address') {
          let address = {
            property: fn,
            operator: tv.operator,
          };
          let isEmpty = isEmptyStringObject(form[fn]);

          if (!isEmpty) {
            address.value = formatAddress(form[fn],'');
          }
          params.conditions.push(address);
          continue;
        }

        if (tv.originalFormType === 'related_task') {
          key = 'taskNo';
        }
        if (tv.formType === 'related_catalog') {
          key = 'id';
          if (tv.fieldName == 'projectName') {
            params.conditions.push({
              property: 'projectId',
              operator: tv.operator,
              value: form[fn][0].id,
              key,
            });
          }
          continue;
        }

        params.conditions.push({
          property: fn,
          operator: tv.operator,
          value: form[fn],
          key,
        });
      }
      // BOM的列表创建时间格式特殊处理
      if(this.tableKey && this.tableKey == 'ITR_BOM_LIST_TABLE'){
        params.timeStart = params.createTimeStart;
        params.timeEnd = params.createTimeEnd;
      }
      delete params.createTime;
      delete params.updateTime;
      return params;
    },
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
      this.saveDataToStorage('column_number', command);
    },
    open() {
      this.visible = true;
    },
    changeDiyFields(e) {
      if (e.length > -1) this.$set(this, 'diyFields', e), (this.show = true);
    },
  },
  components: {
    [SearchSetModal.name]: SearchSetModal,
    // [UsualSelect.name]: UsualSelect,
    SearchForm: {
      name: 'search-form',
      props: {
        fields: {
          type: Array,
          default: () => [],
        },
        formBackup: {
          type: Object,
          default: () => ({}),
        },
        columnNum: {
          type: Number,
          default: 1,
        },
      },
      data() {
        return {
          form: {},
          tableName: 'product',
          show: true,
        };
      },
      mounted() {
        this.buildForm();
      },
      methods: {
        returnData() {
          return Object.assign({}, this.form);
        },
        buildForm() {
          if (Object.keys(this.form).length === this.fields.length) return;
          this.initFormVal();
        },
        initFormVal() {
          let fields = this.fields;
          let form = {};
          let tv = '';

          // fields.forEach((field) => {
          //   tv = '';
          //   // 地址的默认值初始化为对象
          //   if (
          //     field.formType == 'customerAddress'
          //     || field.formType == 'address'
          //   )
          //     tv = {};
          //   if (field.formType == 'date' || field.formType == 'datetime')
          //     tv = [];
          //   if (field.formType === 'link') {
          //     tv = {};
          //   }
          //   if (field.formType === 'tags') {
          //     tv = [];
          //   }
          //   if (field.formType === 'area') {
          //     tv = [];
          //   }
          //   if (field.formType === 'area') {
          //     tv = [];
          //   }
          //   if (field.formType === 'cascader') {
          //     tv = [];
          //   }
          //   form[field.fieldName] = this.formBackup[field.fieldName] || tv;

          //   this.$set(
          //     this.form,
          //     field.fieldName,
          //     this.formBackup[field.fieldName] || tv
          //   );
          // });
          form = Utils.initialize(fields, form);
          this.$set(this, 'form', form);

          return form;
        },
        update(event, action) {
          if (action === 'tags') {
            return this.$set(this.form, 'tags', event);
          }

          if (action === 'dist') {
            return this.$set(this.form, 'area', event);
          }

          const field = event.field;
          if (field.returnData) {
            event.newValue = isFunction(field.returnData)
              ? field.returnData(event.newValue)
              : event.newValue[field.returnData] || event.newValue;
          }
          console.log(field.fieldName, '->', event.newValue);

          this.$set(this.form, field.fieldName, event.newValue);
        },
        createUserInput(event, isTags) {
          if (isTags) {
            return (this.form.tags = event);
          }
          const f = event.field;
          this.form[f.fieldName] = event.keyword;
        },
        renderInput(h, field) {
          const f = {
            ...Object.freeze(field),
          };

          let comp = FormFieldMap.get(f.formType);

          if (
            !comp
            && f.formType !== 'tags'
            && f.formType !== 'area'
            && f.formType !== 'linkman'
          ) {
            return null;
          }

          if (f.formType === 'select') {
            f.setting.isMulti = false;
          }

          let childComp = null;

          if (f.formType === 'tags') {
            childComp = h('biz-team-select', {
              props: {
                value: this.form[f.fieldName],
              },
              on: {
                input: (event) => this.update(event, 'isTags'),
              },
            });
          } else if (f.formType === 'related_catalog') {
            let com_ = f.formType;
            if (
              f.hasOwnProperty('setting')
              && f.setting.hasOwnProperty('formCom')
            )
              com_ = f.setting.formCom;
            com_ = com_.replace(/_/g, '-');
            if (f.fieldName == 'catalogId') com_ = `form-${com_}`;
            childComp = h(com_, {
              props: {
                field: f,
                value: this.form[f.fieldName] ? this.form[f.fieldName] : [],
                disableMap: true,
              },
              on: {
                update: (event) => {
                  console.log(event, 'update');
                  this.update(event);
                },
              },
            });
          } else if ( f.hasOwnProperty('setting')
              && f.setting.hasOwnProperty('formCom')) {
            let com_ = f.formType;
            com_ = f.setting.formCom;
            com_ = com_.replace(/_/g, '-');
            if (f.fieldName == 'catalogId') com_ = `form-${com_}`;
            childComp = h(com_, {
              props: {
                field: f,
                value: this.form[f.fieldName],
                disableMap: true,
              },
              on: {
                update: (event) => {
                  console.log(event, 'update');
                  this.update(event);
                },
              },
            });
          } else if (f.formType === 'linkman') {
            childComp = h('linkman-search', {
              props: {
                field: f,
                value: this.form[f.fieldName],
                disableMap: true,
              },
              on: {
                update: (event) => {
                  this.update(event);
                },
                input: (event) => {
                  this.form[f.fieldName] = event.keyword;
                },
              },
            });
          } else if (f.formType === 'area') {
            childComp = h('base-dist-picker', {
              props: {
                value: this.form[f.fieldName],
              },
              on: {
                input: (event) => this.update(event, 'dist'),
              },
            });
          } else if (f.formType === 'customer') {
            // childComp = h('customer-search', {
            //   props: {
            //     placeholder: '请选择客户',
            //     field: f,
            //     value: this.form[f.fieldName],
            //     disableMap: true,
            //   },
            //   on: {
            //     update: (event) => this.update(event),
            //   },
            // });
            console.log(f, 'usual-select');
            f.setting = {
              ...f.setting,
              ...{
                formCom: 'usual_select',
                searchApi: getCustomerListAsyn,
                searchReturn: 'old',
                searchShowKey: 'name',
                searchShowList: [
                  {
                    key: 'name',
                    label: '名称',
                    isSystem: 1,
                  },
                ],
              },
            };
            childComp = h('usual-select', {
              props: {
                placeholder: '请选择客户',
                field: f,
                value: this.form[f.fieldName],
              },
              on: {
                update: (event) => this.update(event),
              },
            });
          } else if (f.formType === 'user') {
            childComp = h('user-search', {
              props: {
                field: f,
                value: this.form[f.fieldName],
                disableMap: true,
              },
              on: {
                update: (event) => this.update(event),
                input: (event) => {
                  this.form[f.fieldName] = event.keyword;
                },
              },
            });
          } else {
            childComp = h(
              comp.extend && comp.extend[`${f.formType}_search`]
                ? comp.extend[`${f.formType}_search`]
                : comp.build,
              {
                props: {
                  field: f,
                  value: this.form[f.fieldName],
                  disableMap: true,
                  placeholder: Utils.genPlaceholder(f),
                },
                on: {
                  update: (event) => this.update(event),
                },
              }
            );
          }

          return h(
            'form-item',
            {
              props: {
                label: f.displayName,
                needValidate: false,
              },
            },
            [childComp]
          );
        },
      },
      render(h) {
        return (
          <div
            class={`form-item-container ${
              this.columnNum == 2 ? 'two-columns' : ''
            }`}
          >
            {this.fields.map((f) => this.renderInput(h, f))}
          </div>
        );
      },
      components: { ...SettingComponents },
    },
  },
};
</script>
<style lang="scss">
.task-search-forms {
  transition: height 0.5s;
  .form-item {
    width: 340px !important;
  }
}
.el-drawer__header {
  margin-bottom: 0;
  padding: 10px;
  border-bottom: 1px solid #f2f8f7;
}
</style>
<style lang="scss" scoped>
.advanced-search-form {
  overflow: auto;
  padding: 10px 15px 150px 15px;

  height: calc(100%);
  justify-content: space-between;
  overflow-x: hidden;

  .two-columns {
    display: flex;
    flex-wrap: wrap;
    .el-form-item {
      width: 50%;
    }
  }

  .form-item-container {
    justify-content: space-between;
    height: 100%;
    padding-bottom: 64px;
  }

  .form-item {
    label {
      padding-left: 0;
    }

    width: 390px;
  }

  .advanced-search-btn-group {
    display: flex;
    justify-content: flex-end;
    width: 100%;
    position: absolute;
    bottom: 0px;
    background: #fff;
    padding: 15px 20px;

    .base-button {
      margin: 0 10px;
    }
  }
}
.hide {
  overflow: hidden;
  padding: 0;
  height: 0;
  width: 0;
}
.task-search-panel-title {
  height: 54px;
  line-height: 54px;
  padding: 0 15px;
}
.task-search-guide {
  position: relative;
  left: 120px;
  margin-bottom: 20px;
  > div {
    &:first-child {
      width: 0;
      height: 0;
      border-left: 4px solid transparent;
      border-right: 4px solid transparent;
      border-bottom: 6px solid $color-primary-light-6;
      margin-left: 15px;
    }
    &:last-child {
      position: relative;
      width: 267px;
      height: 50px;
      font-size: 14px;
      color: #fff;
      line-height: 50px;
      background-color: $color-primary-light-6;
      box-shadow: 0px 6px 16px 0px rgba(0, 0, 0, 0.08),
        0px 3px 6px -4px rgba(0, 0, 0, 0.12);
      text-align: center;
      border-radius: 4px;
      > span {
        font-size: 12px;
        font-family: fantasy;
        position: absolute;
        top: 8px;
        right: 9px;
        line-height: 10px;
      }
    }
  }
}
</style>

<style lang="scss">
.advanced-search-form {
  overflow: auto;
  padding: 10px 15px 63px 15px;

  height: calc(100% - 52px);
  justify-content: space-between;

  .two-columns {
    display: flex;
    flex-wrap: wrap;
    .el-form-item {
      width: 50%;
    }
  }

  .form-item-container {
    justify-content: space-between;
  }

  .form-item {
    label {
      padding-left: 0;
    }

    width: 390px;
  }

  .advanced-search-btn-group {
    display: flex;
    justify-content: flex-end;
    width: 100%;
    position: absolute;
    bottom: 0px;
    background: #fff;
    padding: 15px 20px;

    .base-button {
      margin: 0 10px;
    }
  }
}

.panel-box {
  height: 100%;
  overflow-y: hidden;
}
.el-drawer__body {
  overflow-y: hidden;
}

.usual-search-form {
  flex: 1;
  .form-item {
    label {
      padding-left: 0;
    }

    width: 390px;
  }
  .form-item-container {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    padding: 10px 15px;
    justify-content: space-between;
  }
}
.advanced-search-btn-group {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  background: #fff;
  padding: 0 20px 15px;
  .base-button {
    margin: 0 10px;
  }
}
</style>